package com.single;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//懒汉式单例
//道高一尺。魔高一丈
public class LazyMan {

    private static boolean xiangmou = false;

    private LazyMan(){

        synchronized (LazyMan.class){
            if (xiangmou == false) {
                xiangmou = true;
            }else {
                throw new RuntimeException("不要试图使用反射破坏");
            }
        }
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    
    private volatile static LazyMan lazyMan;
    
    //双重检测锁模式的 懒汉式单例 DCL
    public static LazyMan getInstance(){
        if (lazyMan==null){
            synchronized (LazyMan.class){
                if (lazyMan==null){
                    lazyMan = new LazyMan();//不是一个原子性操作
                    /*
                    * 1，分配内存空间
                    * 2，执行构造方法，初始化对象
                    * 3，把这个对象指向这个空间
                    *
                    * 可能会指令重排，导致还没有完成构造
                    * */
                }
            }

        }
        return lazyMan;
    }

    //反射
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan instance1 = declaredConstructor.newInstance();
        LazyMan instance = declaredConstructor.newInstance();

        System.out.println(instance);
        System.out.println(instance1);
    }
    
//    //多线程并发
//    public static void main(String[] args) {
//        for (int i = 0; i < 10; i++) {
//            new Thread(()->{
//                LazyMan.getInstance();
//            }).start();
//        }
//    }
}
